import { FormInst, FormValidationError } from 'naive-ui'
import { useI18n } from 'vue-i18n'

import { login } from '@/apis'
import { LoginDto } from '@/apis/auth/type/dto'
import { catchToTuple } from '@/utils'

interface UseLogin {
  formData: LoginDto
  formRef: Ref<FormInst | null>
  getCaptcha: () => Promise<void>
}

export const useLogin = ({ formRef, formData, getCaptcha }: UseLogin) => {
  const loading = ref(false)
  const router = useRouter()
  const i18n = useI18n()

  const handleLogin = () => {
    formRef.value?.validate(async (errors?: FormValidationError[]) => {
      if (errors) return
      loading.value = true
      const [err, data] = await catchToTuple(login(formData))

      if (err) {
        loading.value = false
        window.$message.success('network_error')
        return
      }

      if (data.code !== 200) {
        window.$message.error(data.message)
        loading.value = false
        getCaptcha()
        return
      }

      if (data.data) {
        localStorage.setItem('token', data.data.access_token)
        window.$message.success(i18n.t('common.login_success'))
        router.push('/home')
      }
    })
  }

  return {
    loading,
    handleLogin,
  }
}
